package edu.tyut.game.ui.community

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toFile
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import edu.tyut.game.GameApplication
import edu.tyut.game.MainActivity
import edu.tyut.game.databinding.ActivityPostFriendCircleBinding
import edu.tyut.game.logic.model.FriendCircle
import edu.tyut.game.logic.network.ServiceCreator
import edu.tyut.game.utils.LogUtils
import edu.tyut.game.utils.StatusBarUtils
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import kotlin.streams.toList

class PostFriendCircleActivity : AppCompatActivity() {

    private val tag = this::class.java.name

    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, PostFriendCircleActivity::class.java)
            context.startActivity(intent)
        }
        private const val REQUEST_CODE = 0x000001
    }

    private lateinit var binding: ActivityPostFriendCircleBinding

    private val viewModel by lazy {
        ViewModelProvider(this)[PostFriendCircleViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        binding = ActivityPostFriendCircleBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 隐藏ActionBar
        // 状态栏透明
        StatusBarUtils.setTranslucentStatusBar(this)

        // 选择图片
        // 选择图片
        // Registers a photo picker activity launcher in multi-select mode.
        // In this example, the app lets the user select up to 5 media files.
        val imageList = mutableListOf<Uri>()
        val pickMultipleMedia =
            registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(9)) { uris ->
                // Callback is invoked after the user selects media items or closes the
                // photo picker.
                if (uris.isNotEmpty()) {
                    Log.d("PhotoPicker", "Number of items selected: ${uris.size}")
                    imageList.clear()
                    imageList.addAll(uris)
                    val adapter =
                        PostImageViewAdapter(this@PostFriendCircleActivity, imageList)
                    binding.images.adapter = adapter
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        val gridLayoutManager = GridLayoutManager(this, 3, RecyclerView.VERTICAL, false)
        gridLayoutManager.orientation = RecyclerView.VERTICAL
        binding.images.layoutManager = gridLayoutManager
        binding.selectPic.setOnClickListener {
            // For this example, launch the photo picker and let the user choose images
            // and videos. If you want the user to select a specific type of media file,
            // use the overloaded versions of launch(), as shown in the section about how
            // to select a single media item.
            pickMultipleMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }

        // 发送朋友圈
        binding.post.setOnClickListener {
            val uid = GameApplication.loginUser?.id ?: 1
            val username = GameApplication.loginUser?.username ?: "admin"
            val gender = GameApplication.loginUser?.gender ?: "男"
            val avatarPath = GameApplication.loginUser?.avatarPath
            val content = binding.content.text.toString().trim()
            if (content.isEmpty() || content.isBlank()) {
                Toast.makeText(this, "内容不能为空😊~", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            val friendCircle = FriendCircle(0, uid, username, gender, avatarPath ?: "/image/image.jpg", content, "", 0)
            postFriendCircle(imageList, friendCircle)
            // 退出
            Toast.makeText(this, "发送朋友圈成功😊~", Toast.LENGTH_LONG).show()
            this.onBackPressedDispatcher.onBackPressed()
        }

        viewModel.resFriendCircle.observe(this) { res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true) {
                LogUtils.d(tag, "朋友圈发布成功")
            }
        }

        // 取消发布朋友圈
        binding.cancel.setOnClickListener {
            this.onBackPressedDispatcher.onBackPressed()
        }

    }

    private fun postFriendCircle(files: List<Uri>, friendCircle: FriendCircle) {
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
        for (file in files) {
            val inputStream = contentResolver.openInputStream(file)
            val requestFile: RequestBody =
                RequestBody.create(
                    MediaType.parse("image/*"),
                    inputStream!!.readBytes()
                ) // 图片文件不能超过2G
            val str = file.toString()
            var name = str.substring(str.lastIndexOf("/") + 1)
            if (!name.contains(".")) name = "$name.jpg"
            builder.addFormDataPart("files", name, requestFile)
            inputStream.close()
        }
        val gson = Gson()
        builder.addFormDataPart("content", gson.toJson(friendCircle))
        val parts = builder.build().parts()
        // TODO 发送朋友圈
        LogUtils.d(tag, "${gson.toJson(friendCircle)}: 发送朋友圈...")
        viewModel.postFriendCircle(parts)
    }
}